package com.hdjk.view.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;

public class ConnectionUtil {

	/**
	 * 获取wifi名字
	 * @param context
	 * @return
	 */
	public static String getWifiName(Context context) {
		String wifiName="";
		if(isWifiConnected(context)){
			WifiManager wifiManager = (WifiManager) context
					.getSystemService(Context.WIFI_SERVICE);
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			wifiName = (wifiInfo != null ? wifiInfo.getSSID() : "");
			// 取到的wifi名称会有双引号，需要自己去掉
			if (wifiName != null && !wifiName.equals("")
					&& wifiName.startsWith("\"") && wifiName.endsWith("\"")) {
				if (wifiName.length() > 2) {
					wifiName = wifiName.substring(1, wifiName.length() - 1);
				}
			}
		}
		
		return wifiName;
	}
	
	/**
	 * 判断是否已连接wifi信号
	 * @param context
	 * @return
	 */
	public static boolean isWifiConnected(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo wifiNetworkInfo = connectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		if (wifiNetworkInfo != null && wifiNetworkInfo.isConnected()) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isConnection(Context context) {
		ConnectivityManager mConnectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		TelephonyManager mTelephony = (TelephonyManager) context
				.getSystemService(context.TELEPHONY_SERVICE);
		NetworkInfo info = mConnectivity.getActiveNetworkInfo();
		if (info == null || !mConnectivity.getBackgroundDataSetting()) {
			return false;
		}
		int netType = info.getType();
		int netSubtype = info.getSubtype();
		if (netType == ConnectivityManager.TYPE_WIFI) {
			return info.isConnected();
		} else if (netType == ConnectivityManager.TYPE_MOBILE) {
			return info.isConnected();
		} else {
			return false;
		}
	}
}
